package com.headwire.kw.helpers.qxml;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class QuickXML {
	public static void printDocument(QXElement root, QuickXMLWriter xml) {
		printElement(root,xml);
	}
	
	public static QXElement loadDocument(File xml) throws IOException, SAXException {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		
		//out = new OutputStreamWriter (System.out, "UTF8");
		SAXParser saxParser;
		try {
			saxParser = factory.newSAXParser();
		} catch (ParserConfigurationException e) {
			// this shouldn't happen because we didn't try to configure it at all
			throw new RuntimeException("Unknown problem: "+e.getMessage(),e);
		}
		SimpleXMLParser sxp = new SimpleXMLParser();
        saxParser.parse( xml, sxp);
        return sxp.root;
	}
	
	private static void printElement(QXElement elem, QuickXMLWriter xml) {
		if(elem == null) {
			return;
		}
		xml.startElement(elem.getName());
		if(elem.attrs != null) {
			for(QXAttribute a : elem.attrs) {
				xml.attribute(a.getName(), a.getValue());
			}
		}
		if(elem.text!= null) {
			xml.text(elem.getText());
		}
		if(elem.children != null) {
			for(QXElement c : elem.children) {
				printElement(c,xml);
			}
		}
		xml.endElement();
	}
}
